package org.example.lanchain.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.lanchain.service.UserService;
import org.example.lanchain.tools.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        try {
            // 从请求头中提取JWT令牌
            String jwt = extractJwtFromRequest(request);
            
            if (StringUtils.hasText(jwt) && jwtUtil.validateToken(jwt)) {
                // 从JWT中获取用户ID
                Long userId = jwtUtil.getUserIdFromToken(jwt);
                
                if (userId != null) {
                    // 获取用户信息
                    org.example.lanchain.bean.User user = userService.getUserByToken(jwt);
                    
                    if (user != null) {
                        // 创建UserDetails对象
                        UserDetails userDetails = createUserDetails(user);
                        
                        // 创建认证令牌
                        UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        // 设置认证信息到Security上下文
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("无法设置用户认证", e);
        }
        
        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中提取JWT令牌
     */
    private String extractJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 创建UserDetails对象
     */
    private UserDetails createUserDetails(org.example.lanchain.bean.User user) {
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password("") // 不存储密码
                .authorities("ROLE_" + user.getRole().toUpperCase())
                .accountExpired(!"active".equals(user.getStatus()))
                .accountLocked("banned".equals(user.getStatus()))
                .credentialsExpired(false)
                .disabled(!"active".equals(user.getStatus()))
                .build();
    }
} 